import React, { useEffect, useRef, useState } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Radio,
  Space,
  Button,
  Upload,
  message,
} from 'antd';
import { Link } from 'react-router-dom';
import Channel from './../../components/channel';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss';
import { PlusOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import Modal from 'antd/lib/modal/Modal';
import { publishArticles, articlesDetail, artilesEdit } from 'api/channel';
import history from 'utils/history';

export default function ArticlePublish(props) {
  // console.log(25, props);
  // 用ref来保存数据
  const draftRef = useRef(false);
  // const [formRef] = Form.useForm();
  const formRef = useRef({});
  // console.log(formRef);
  const [filelist, setFilelist] = useState([]);
  const [showPreview, setShowPreview] = useState(false);
  const [previewUrl, setPreviewUrl] = useState('');

  // 上传图片函数
  const uploadImages = ({ file, fileList }) => {
    // console.log(fileList);
    setFilelist(fileList);
  };

  const [type, setType] = useState(1);
  // 控制图片上传数量
  const changeImageType = (e) => {
    // console.log(34, e);
    setType(e.target.value);
  };

  // 预览图片
  const handlePreview = (file) => {
    // console.log(41, file);
    const url = file.url || file.response.data.url;
    setShowPreview(true);
    setPreviewUrl(url);
  };

  const handleCancel = () => {
    setShowPreview(false);
    setPreviewUrl('');
  };

  // 切换type时，图片显示不同张
  const showList = filelist.filter((item, index) => {
    if (type === 0) return false;
    if (type === 1) return index === 0;
    return true;
  });

  // 上传前图片校验
  const beforeUpload = (file) => {
    const whiteList = ['image/png', 'image/jpeg'];
    // console.log(54, file);
    if (file.size >= 1024 * 500) {
      message.warning('上传的图片不能超过5M');
      // 阻止发请求，也不显示在前端页面
      return Upload.LIST_IGNORE;
    }
    if (!whiteList.includes(file.type)) {
      message.warn('只能上传jpg或者png的图片');
      return Upload.LIST_IGNORE;
    }
    return true;
  };
  // 获取表单数据
  const onFinish = async (values) => {
    // console.log(69, values);
    // console.log(69, filelist);
    // 验证选的图片类型和上传的图片数量对不对
    if (type !== showList.length) {
      return message.warning('上传的图片数量不对');
    }

    // 存储发送请求要用到的数据(要利用showList来遍历)
    const coverImages = showList.map((item) => {
      // console.log(86, item);
      // 新增和编辑的图片路径不一样，编辑时候是item.url，新增时候是item.response.data.url
      return item.url || item.response.data.url;
    });
    const cover = {
      type,
      images: coverImages,
    };
    // 发请求(根据是否有id来判断是编辑还是新增)
    if (props.location.state && props.location.state.id) {
      // console.log(96, draftRef.current);
      await artilesEdit({
        ...values,
        cover,
        draft: draftRef.current,
        id: props.location.state.id,
      });
    } else {
      await publishArticles({
        ...values,
        cover,
        draft: draftRef.current,
      });
    }

    // console.log(78, res);
    // 跳回文章列表页
    history.push('/list');
    // 提示用户
    message.success('操作成功');
    // 清空表单数据
  };

  // 通过id获取要编辑的文章数据
  const getArticlesDetail = async () => {
    const res = await articlesDetail(props.location.state.id);
    // console.log(110, res);
    const values = {
      ...res.data,
      type: res.data.cover.type,
    };
    // 回显表单的值
    // formRef.setFieldsValue(values);
    formRef.current.setFieldsValue(values);
    // 回显图片
    const fileImg = res.data.cover.images.map((item) => ({ url: item }));
    // console.log(118, fileImg);
    // console.log(type);
    setType(res.data.cover.type);
    // console.log(119, filelist);
    setFilelist(fileImg);
  };

  // 在钩子函数中调用请求
  useEffect(() => {
    if (props.location.state && props.location.state.id) {
      getArticlesDetail();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return (
    <div
      className={styles.ArticlePublish}
      style={{
        padding: 24,
        height: 'calc(100vh - 64px)',
        overflow: 'auto',
      }}
    >
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {props.location.state && props.location.state.id
                ? '编辑文章'
                : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单 */}
        <Form
          // form={formRef}
          ref={formRef}
          size="large"
          labelCol={{ span: 4 }}
          onFinish={onFinish}
          validateTrigger={['onBlur', 'onChange']}
          // 设置默认值，让校验通过
          initialValues={{
            // title: '测试标题',
            // channel_id: 0,
            type: 1,
            content: '测试内容',
          }}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '标题不能为空' }]}
          >
            <Input placeholder="请输入文章标题" />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '标题不能为空' }]}
          >
            <Channel allowClear></Channel>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                // message: '请输入文章内容',
                required: true,
                validator: (_, value) => {
                  // console.log(168, value);
                  return !value || value === '<p><br></p>'
                    ? Promise.reject(new Error('内容不能为空'))
                    : Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill
              theme="snow"
              placeholder="请输入文章内容..."
            ></ReactQuill>
          </Form.Item>

          <Form.Item label="封面" name="type">
            <Radio.Group onChange={changeImageType}>
              <Radio value={1}>单图</Radio>
              <Radio value={0}>无图</Radio>
              <Radio value={3}>三图</Radio>

              {/* <Radio value={-1}>自动</Radio> */}
            </Radio.Group>
          </Form.Item>
          {/* 图片上传 */}
          <Form.Item wrapperCol={{ offset: 4 }}>
            {
              <Upload
                listType="picture-card"
                name="image"
                action={`${baseURL}/upload`}
                onChange={uploadImages}
                fileList={showList}
                onPreview={handlePreview}
                beforeUpload={beforeUpload}
              >
                {filelist.length < type && <PlusOutlined />}
              </Upload>
            }
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {props.location.state && props.location.state.id
                  ? '编辑文章'
                  : '发布文章'}
              </Button>
              <Button
                htmlType="submit"
                onClick={() => {
                  draftRef.current = true;
                }}
              >
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      {/* 弹窗，用于显示预览的图片 */}
      <Modal
        visible={showPreview}
        title="图片预览"
        footer={null}
        onCancel={handleCancel}
      >
        <img alt="example" style={{ width: '100%' }} src={previewUrl} />
      </Modal>
    </div>
  );
}
